/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-11-06     BalanceTWK   first version
 */

#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>

#if defined(RT_USING_FAL)
#include <fal.h>

#if defined(RT_USING_DFS)
#include <dfs_fs.h>
#define FS_PARTITION_NAME   "filesystem"    /**<  将fal的"filesystem"分区挂载为文件系统 */
#define FS_TYPE             "elm"           /**<  FatFs文件系统 */
#endif

#endif

#define DBG_SECTION_NAME               "main"
#define DBG_LEVEL                      DBG_LOG
#include <rtdbg.h>

int main(void)
{
    /**<  启动fal组件及文件系统 */
#if defined(RT_USING_FAL)
    int ret = fal_init();
    if(0 > ret)
    {
        LOG_E("fal_init failed (ret=%d)", ret);
    }
#if defined(RT_USING_DFS)
    rt_device_t blkdev = fal_blk_device_create(FS_PARTITION_NAME);
    if (!blkdev)
    {
        LOG_E("Can't create a mtd device on '%s' partition.", FS_PARTITION_NAME);
    }
    else
    {
        /* 挂载文件系统 */
        if (dfs_mount(FS_PARTITION_NAME, "/", FS_TYPE, 0, 0) == 0)
        {
            LOG_I("Filesystem initialized!");
        #if defined(PKG_USING_WEBNETPRO)
            extern void webnet_test(void);
            webnet_test();
        #endif
        }
        else
        {
            /* 格式化文件系统 */
            LOG_I("df_mkfs(%s, %s)", FS_TYPE, FS_PARTITION_NAME);
            if(0 == dfs_mkfs(FS_TYPE, FS_PARTITION_NAME))
            {
                /* 挂载文件系统 */
                if (dfs_mount(FS_PARTITION_NAME, "/", FS_TYPE, 0, 0) == 0)
                {
                    LOG_I("Filesystem initialized!");
                #if defined(PKG_USING_WEBNET)
                    extern void webnet_test(void);
                    webnet_test();
                #endif
                }
                else
                {
                    LOG_E("Failed to initialize filesystem!");
                }
            }
            else
            {
                LOG_E("dfs_mkfs failed !!");
            }
        }
    }    
#endif
#endif

    /* defined the LED1 pin: PB0 (LED0--PB1--green, LED1--PB0--red) */
    #define LED_PIN    GET_PIN(B, 0)
    rt_pin_mode(LED_PIN, PIN_MODE_OUTPUT);

    while (1)
    {
        rt_pin_write(LED_PIN, PIN_HIGH);
        rt_thread_mdelay(1000);
        rt_pin_write(LED_PIN, PIN_LOW);
        rt_thread_mdelay(1000);
    }

    return RT_EOK;
}
